<template xmlns:display="http://www.w3.org/1999/xhtml">
  <div class="register">
      <div class="bg">
        <div style="display:flex; width:300px; background-color:white; border-radius:5px; box-shadow:0 0 10px rgba(0,0,0,.1); padding:20px;">

          <el-form ref="formRef" status-icon :model="data.form" :rules="data.rules" >
            <div style="margin:15px 0; text-align:center; font-size:24px; font-weight: bold;">注 册</div>
            <el-form-item prop="username"  >
              <el-input v-model="data.form.username" autocomplete="off" prefix-icon="User" placeholder="请输入账号"/>
            </el-form-item>
            <el-form-item prop="password" >
              <el-input v-model="data.form.password" show-password autocomplete="off" prefix-icon="Lock" placeholder="请输入密码"/>
            </el-form-item>
            <el-form-item prop="confirmPassword" >
              <el-input v-model="data.form.confirmPassword" show-password autocomplete="off" prefix-icon="Lock" placeholder="请再次输入密码"/>
            </el-form-item>
            <el-button type="success" style="width:240px; margin-left:10px; padding-top:15px;" @click="register">注 册</el-button>
            <div style="text-align: right; padding-top:20px;">
              已经有账号？去 <a style="color:#3535e6; " href="/login">登录</a>
            </div>
          </el-form>

        </div>
      </div>
  </div>


</template>

<script setup>
import { reactive, ref } from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";
import router from "@/router/index.js";

const validatePass = (rules, value, callback) => {
  //value表示用户输入的确认密码
  if (value !== data.form.password) {
    callback(new Error("两次密码不匹配！"))
  } else {
    callback()
  }
}

const data = reactive( {
  password:null,
  username:null,
  form: {},
  rules: {
    username:[
      {required:true, message:'请输入账号', trigger:"blur"}
    ],
    password:[
      {required:true, message:'请输入密码', trigger:"blur"},
      {min: 6, message:'密码最少六位', trigger:"blur"}
    ],
    confirmPassword:[
      {required:true, message:'请再次确认密码', trigger:"blur"},
      {validator:validatePass,trigger:"blur"}
    ],
  },
})

const formRef = ref({});

const register = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      request.post('/register', data.form).then(res => {
        if(res.code === '200') {
          ElMessage.success("注册成功")
          router.push('/login')
        }else{
          ElMessage.error(res.msg);
        }
      })
    }
  })
}


</script>

<style scoped>
.bg{
  height:100vh;
  display:flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  background-image: url('@/assets/imgs/bg1.jpg');
  background-size: cover;

}
</style>